From 1504af077935a0bfd1b1b59f77d8b1cd89f913b5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?R=C3=A9mi=20Verschelde?= <rverschelde@gmail.com>
Date: Mon, 10 Dec 2018 13:05:15 +0100
Subject: [PATCH] CMake: Allow linking against system-installed SPIRV-Tools

Fixes #1585.
---
 CMakeLists.txt       |  7 ++++++-
 SPIRV/CMakeLists.txt | 21 +++++++++++++--------
 2 files changed, 19 insertions(+), 9 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index ada2b8fb9..22243f491 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -320,7 +320,12 @@ if(BUILD_EXTERNAL AND IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/External)
     add_subdirectory(External)
 endif()
 
-if(NOT TARGET SPIRV-Tools-opt)
+find_package(PkgConfig)
+if(PkgConfig_FOUND)
+    pkg_check_modules(SPIRV-Tools SPIRV-Tools)
+endif()
+# Former would be system-installed, later is from External
+if(NOT SPIRV-Tools_FOUND AND NOT TARGET SPIRV-Tools-opt)
     set(ENABLE_OPT OFF)
 endif()
 
diff --git a/SPIRV/CMakeLists.txt b/SPIRV/CMakeLists.txt
index d699daddb..28beb47bb 100644
--- a/SPIRV/CMakeLists.txt
+++ b/SPIRV/CMakeLists.txt
@@ -91,14 +91,19 @@ if(WIN32 AND BUILD_SHARED_LIBS)
 endif()
 
 if(ENABLE_OPT)
-    target_include_directories(SPIRV
-        PRIVATE ${spirv-tools_SOURCE_DIR}/include
-        PRIVATE ${spirv-tools_SOURCE_DIR}/source
-    )
-    target_link_libraries(SPIRV PRIVATE MachineIndependent SPIRV-Tools-opt)
-    target_include_directories(SPIRV PUBLIC
-        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../External>
-        $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/External>)
+    if(SPIRV-Tools_FOUND)
+        target_include_directories(SPIRV PUBLIC ${SPIRV-Tools_INCLUDEDIR})
+        target_link_libraries(SPIRV glslang ${SPIRV-Tools_LIBRARIES})
+    else()
+        target_include_directories(SPIRV
+            PRIVATE ${spirv-tools_SOURCE_DIR}/include
+            PRIVATE ${spirv-tools_SOURCE_DIR}/source
+        )
+        target_link_libraries(SPIRV PRIVATE MachineIndependent SPIRV-Tools-opt)
+        target_include_directories(SPIRV PUBLIC
+            $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../External>
+            $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/External>)
+    endif()
 else()
     target_link_libraries(SPIRV PRIVATE MachineIndependent)
 endif(ENABLE_OPT)
